<template>
  <div v-loading.fullscreen.lock="loading">
    <div class="page-header">
      <p>选项异常处理</p>
      <div class="page-header-back" @click="$router.back()">退出</div>
    </div>

    <div class="container">
      <div class="container-left">
        <div class="count">
          <div class="ycl" style="width: 100%">
            未处理({{ tableData.length }})
          </div>
          <!-- <div class="wcl">已处理</div> -->
        </div>
        <el-table
          border
          :data="tableData"
          @row-click="rowClick"
          :cell-class-name="isTableActive"
        >
          <el-table-column label="流水号" align="center" prop="serialNo" />
          <el-table-column
            label="异常数"
            align="center"
            prop="optionAbnormalCount"
          />
          <el-table-column label="异常状态" align="center">
            <el-tag type="danger" size="mini">选项异常</el-tag>
          </el-table-column>
        </el-table>
      </div>

      <div class="container-right" ref="containerRight">
        <el-button class="allBlank" type="primary" @click="allBlank"
          >未选置空</el-button
        >
        <div class="scroll-box" ref="scrollBox">
          <div class="yc-box">
            <img
              class="ycxx-image"
              v-if="tableData.length > 0 && teampleData"
              :src="imgSrc"
              alt=""
              :style="`width:${teampleData.width}px;height:${teampleData.height}px;`"
            />
            <template v-if="currentImgKey==1">
              <div
                class="yc-item"
                v-for="(item, index) in ycxx"
                :key="item.id"
                :style="`width:${item.width}px;height:${item.height}px;top:${item.y}px;left:${item.x}px`"
                :class="{ active: ycxxIndex == index, processed: ycl(item.id) }"
                @click="switchYcxxIndex(index)"
              ></div>
            </template>
          </div>
          <!-- 切换正反面 -->
          <div class="pageImage">
            <span @click="changeImage('1')" :class="{'is-active':currentImgKey == '1' }">1</span>
            <span @click="changeImage('2')" :class="{'is-active':currentImgKey == '2'}">2</span>
          </div>
        </div>
      </div>
    </div>
    <div class="page-bottom">
      <p>已处理/总异常:{{ answerList.length }}/{{ ycxx.length }}</p>
      <el-select size="small" @change="switchYcxxIndex" v-model="ycxxIndex">
        <el-option
          v-for="(item, index) in ycxx"
          :key="item.id"
          :label="`${item.questionName}（${selectDictLabel(
            dict.type.question_type,
            item.questionType
          )}） ${ycl(item.id)}`"
          :value="index"
        ></el-option>
      </el-select>
      <div class="yc-answer-box">
        <!-- 单选 -->
        <template v-if="ycxx[ycxxIndex] && ycxx[ycxxIndex].questionType == 1">
          <div
            v-for="item in ycxx[ycxxIndex].optionCount"
            :key="item"
            class="yc-answer-item"
            :class="{
              active: ycxx[ycxxIndex].daan == optionList[item - 1],
            }"
            @click="answerClick(optionList[item - 1])"
          >
            {{ optionList[item - 1] }}
          </div>
          <div
            class="yc-answer-item danger"
            :class="{ active: ycxx[ycxxIndex].daan == '0' }"
            @click="answerClick('0')"
          >
            空 (Num0)
          </div>
          
        </template>

        <!-- 多选 -->
        <template v-if="ycxx[ycxxIndex] && ycxx[ycxxIndex].questionType == 2">
          <div
            v-for="item in ycxx[ycxxIndex].optionCount"
            :key="item"
            class="yc-answer-item"
            :class="{
              active:
                ycxx[ycxxIndex].daan &&
                ycxx[ycxxIndex].daan.indexOf(optionList[item - 1]) != -1,
            }"
            @click="answerClick(optionList[item - 1], true)"
          >
            {{ optionList[item - 1] }}
          </div>
          <div
            class="yc-answer-item danger"
            :class="{ active: ycxx[ycxxIndex].daan == '0' }"
            @click="answerClick('0', true)"
          >
            空 (Num0)
          </div>
        </template>

        <!-- 判断 -->
        <template v-if="ycxx[ycxxIndex] && ycxx[ycxxIndex].questionType == 3">
          <div
            class="yc-answer-item"
            :class="{
              active: ycxx[ycxxIndex].daan == 'T',
            }"
            @click="answerClick('T')"
          >
            对
          </div>
          <div
            class="yc-answer-item"
            :class="{
              active: ycxx[ycxxIndex].daan == 'F',
            }"
            @click="answerClick('F')"
          >
            错
          </div>
          <div
            class="yc-answer-item danger"
            :class="{ active: ycxx[ycxxIndex].daan == '0' }"
            @click="answerClick('0')"
          >
            空 (Num0)
          </div>
        </template>
        <div class="yc-answer-item danger" @click="absentexam">
             缺考
          </div>
      </div>

      <el-button
        type="success"
        @click="switchYcxxIndex(ycxxIndex + 1)"
        :disabled="tableData.length == 0"
        v-if="ycxxIndex != ycxx.length - 1"
        >下一个 (Enter)</el-button
      >
      <el-button
        v-else
        type="primary"
        @click="submit"
        :disabled="answerList.length != ycxx.length"
        >提 交 (Enter)</el-button
      >
      <!-- <el-button
        style="margin-left: auto"
        type="primary"
        :disabled="tableData.length == 0 || answerList.length != ycxx.length"
        @click="submit"
        >提 交</el-button
      > -->
    </div>
  </div>
</template>

<script>
import {
  scanRecognitionRecord,
  scanSelectAbnormalAll,
  scanHandlerAbsenceStatus,
  scanAbsence
} from "@/api/xmgl/smgl";
import { teampleHW } from "@/api/common";
export default {
  dicts: ["question_type"],
  data() {
    return {
      loading: false,
      xmxx: {},
      tableData: [],
      tableActiceId: "",
      ycxx: [],
      ycxxIndex: 0,

      optionList: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],

      teampleData: null,
      currentImgKey:1,
    };
  },
  computed: {
    answerList: function () {
      let arr = this.ycxx.filter((item) => {
        return item.daan;
      });
      return arr.map((item) => {
        return {
          questionId: item.questionId,
          id: item.id,
          answers:
            item.questionType == 2 && item.daan && item.daan != "0"
              ? item.daan.sort((a, b) => a.localeCompare(b)).join(" ")
              : item.daan,
        };
      });
    },
    imgSrc: function () {
      if(this.currentImgKey==1){
          return this.tableData.filter((item) => {
            return item.id == this.tableActiceId;
          })[0].frontImgPath;
      }else{
        return this.tableData.filter((item) => {
            return item.id == this.tableActiceId;
          })[0].backImgPath;
      }
    },
  },
  created() {
    window.addEventListener("keyup", this.keyUp);
    this.$store.dispatch("getXmxx").then((res) => {
      this.xmxx = res;

      this.loading = true;

      teampleHW({
        templateId: this.$route.query.templateId,
      }).then((res) => {
        this.teampleData = res.data[0];
        scanRecognitionRecord({
          examId: this.xmxx.id,
          examSchoolId: this.$route.query.examSchoolId
            ? [this.$route.query.examSchoolId]
            : [],
          examSubjectId: this.$route.query.examSubjectId || null,
          examScanDetails: {
            abnormalOption: "1",
          },
          pageNum: 1,
          pageSize: 9999,
        })
          .then((res) => {
            if (res.data.records.length > 0) {
              this.tableActiceId = res.data.records[0].id;
              this.getYcxx();
            }
            this.tableData = res.data.records;
          })
          .finally(() => {
            this.loading = false;
          });
      });
    });
  },
  methods: {
    //切换正反面
    changeImage(num){
      this.currentImgKey = num
    },
    //缺考
    absentexam(){
      // qk(id, missingExam) {
      this.$modal
        .confirm(`请确认进行缺考操作`)
        .then(() => {
          scanAbsence({
            ids: [this.tableActiceId],
            missingExam: 1,
            type: 2,
          }).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.updateActive()
          });
        });
    // },
    },
    getYcxx() {
      this.loading = true;
      scanSelectAbnormalAll({
        examScanDetailId: this.tableActiceId,
      })
        .then((res) => {
          this.ycxx = res.data;
          this.ycxxIndex = 0;

          this.$nextTick(() => {
            this.scroll();
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    scroll() {
      let x =
        this.ycxx[this.ycxxIndex].x - this.$refs.containerRight.offsetWidth / 2;
      let y =
        this.ycxx[this.ycxxIndex].y -
        this.$refs.containerRight.offsetHeight / 2;

      this.$refs.scrollBox.scrollTo({
        top: y,
        left: x,
      });
    },

    rowClick(row) {
      if (row.id != this.tableActiceId) {
        this.tableActiceId = row.id;
        this.getYcxx();
      }
    },

    isTableActive(row) {
      if (row.row.id == this.tableActiceId) {
        return "table-active";
      } else {
        return "";
      }
    },

    switchYcxxIndex(index) {
      this.ycxxIndex = index;
      this.scroll();
    },

    answerClick(answer, isMultiple) {
      let ycxx;
      if (isMultiple) {
        ycxx = JSON.parse(JSON.stringify(this.ycxx));
        if (answer == "0") {
          ycxx[this.ycxxIndex].daan = "";
        }
        if (ycxx[this.ycxxIndex].daan) {
          let i = ycxx[this.ycxxIndex].daan.indexOf(answer);
          if (i == -1) {
            ycxx[this.ycxxIndex].daan.push(answer);
          } else {
            ycxx[this.ycxxIndex].daan.splice(i, 1);
          }
          if (ycxx[this.ycxxIndex].daan.length == 0) {
            ycxx[this.ycxxIndex].daan = "";
          }
        } else {
          ycxx[this.ycxxIndex].daan = [answer];
        }
        this.ycxx = ycxx;
      } else {
        ycxx = JSON.parse(JSON.stringify(this.ycxx));
        ycxx[this.ycxxIndex].daan = answer;
        this.ycxx = ycxx;
      }
    },
    allBlank() {
      this.ycxx = this.ycxx.map((item) => {
        return {
          ...item,
          daan: item.daan ? item.daan : "0",
        };
      });

      this.ycxxIndex = this.ycxx.length - 1;
    },
    submit() {
      this.loading = true;
      let answerList = JSON.parse(JSON.stringify(this.answerList));
      answerList = answerList.map((item) => {
        return {
          ...item,
          answers: item.answers == "0" ? "" : String(item.answers).replace(/\s+/g, ''),
        };
      });
      scanHandlerAbsenceStatus({
        examScanDetailsId: this.tableActiceId,
        examScanQuestions: answerList,
      })
        .then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.updateActive()
        })
        .finally(() => {
          this.loading = false;
        });
    },
    updateActive(){
      let tableData = JSON.parse(JSON.stringify(this.tableData));
          let index = tableData.findIndex((item) => {
            return item.id == this.tableActiceId;
          });
          if (tableData.length == 1) {
            tableData = [];
            this.ycxx = [];
            this.ycxxIndex = 0;
          } else if (tableData[index + 1]) {
            this.tableActiceId = tableData[index + 1].id;
            this.getYcxx();
          } else {
            this.tableActiceId = tableData[0].id;
            this.getYcxx();
          }
          tableData.splice(index, 1);
          this.tableData = tableData;
    },
    ycl(id) {
      return this.answerList.some((item) => {
        return item.id == id;
      })
        ? "已选"
        : "";
    },

    keyUp(event) {
      if (event.key == "0") {
        this.answerClick("0", true);
      } else if (event.key === "Enter") {
        if (this.ycxxIndex != this.ycxx.length - 1) {
          this.switchYcxxIndex(this.ycxxIndex + 1);
        } else if (this.answerList.length != this.ycxx.length) {
          this.$modal.msgError("有未处理的异常");
        } else {
          this.submit();
        }
      }
    },
  },

  beforeDestroy() {
    window.removeEventListener("keyup", this.keyUp);
  },
};
</script>
<style >
.table-active {
  background: #288f411a;
}
</style>
<style lang="scss" scoped>
.page-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
  background: #1a48db;
  font-size: 16px;
  padding: 0 24px 0 44px;

  p {
    margin: 0;
  }

  .page-header-back {
    width: 76px;
    height: 32px;
    background: #ffffff;
    border-radius: 16px;
    line-height: 32px;
    text-align: center;
    color: #1a48db;
    font-size: 16px;
    cursor: pointer;

    &:active {
      opacity: 0.8;
    }
  }
}
.container {
  height: calc(100vh - 50px);
  display: flex;

  .container-left {
    width: 256px;
    height: 100%;
    background: #ffffff;
    overflow: auto;

    .count {
      width: 100%;
      display: flex;

      div {
        width: 50%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 14px;
      }
      .ycl {
        color: #e93a40;
        background: #e93a401a;
      }
      .wcl {
        color: #288f41;
        background: #288f411a;
      }
    }
  }

  .container-right {
    width: calc(100% - 256px);
    height: calc(100vh - 100px);
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    .allBlank {
      position: absolute;
      right: 20px;
      top: 20px;
      z-index: 9;
    }
    .scroll-box {
      width: 100%;
      height: 100%;
      overflow: auto;
      position: relative;
      .yc-box {
        position: relative;
        .yc-item {
          border: 3px solid #f56c6c;
          background: rgba(245, 108, 108, 0.2);
          position: absolute;
          cursor: pointer;
          &.active {
            background: transparent;
          }
          &.processed {
            border-color: #13ce66;
            background: transparent;
          }
        }
      }
    }
  }
}

.page-bottom {
  width: calc(100vw - 256px);
  justify-content: flex-start;
  p {
    color: #606266;
    font-size: 14px;
    margin-right: 20px;
  }
  .yc-answer-box {
    display: flex;
    margin: 0 20px;
    .yc-answer-item {
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background: #f2f3ff;
      cursor: pointer;
      color: #1a48db;

      & + .yc-answer-item {
        margin-left: 10px;
      }

      &.active {
        color: #ffffff;
        background: #1a48db;
      }

      &.danger {
        background: #fdeeef;
        color: #ec555a;
        width: 100px;
      }

      &.danger.active {
        background: #ec555a;
        color: #fff;
      }
    }
  }
}
.pageImage{
  display: flex;
  align-items: center;
  position:fixed;
  right:15px;
  bottom:65px;
}
.pageImage .is-active{
  background: #1a48db;
  color: #fff;
}

.pageImage span{
  display: inline-block;
  width:30px;
  height:30px;
  background: transparent;
  border-radius:5px;
  text-align: center;
  border: 1px solid #1a48db;
  line-height:30px;
  font-size:14px;
  color:#1a48db;
  margin-left:10px;
  cursor: pointer;
}
</style>
